package com.examstack.portal.controller.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonProcessingException;
import org.springframework.amqp.AmqpException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.examstack.common.Constants;
import com.examstack.common.domain.exam.AnswerSheet;
import com.examstack.common.domain.exam.AutoCPaper;
import com.examstack.common.domain.exam.Exam;
import com.examstack.common.domain.exam.ExamHistory;
import com.examstack.common.domain.exam.ExamPaper;
import com.examstack.common.domain.exam.Message;
import com.examstack.common.domain.exam.PaperCreatorParam;
import com.examstack.common.domain.question.Field;
import com.examstack.common.domain.question.KnowledgePoint;
import com.examstack.common.domain.question.QuestionStatistic;
import com.examstack.common.domain.question.QuestionStruts;
import com.examstack.common.util.DateUtil;
import com.examstack.portal.persistence.ExamPaperMapper;
import com.examstack.portal.persistence.QuestionMapper;
import com.examstack.portal.security.UserInfo;
import com.examstack.portal.service.ExamPaperService;
import com.examstack.portal.service.ExamService;
import com.examstack.portal.service.QuestionService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;

@Controller
public class ExamAction {
	
	@Autowired
	private ExamService examService;
	@Autowired
	private QuestionService questionService;
	@Autowired
	private ExamPaperService examPaperService;
	@Autowired
	private QuestionMapper questionMapper;
	@Autowired
	private ExamPaperMapper examPaperMapper;
	
	@Autowired
	private org.springframework.amqp.core.AmqpTemplate qmqpTemplate;
	/**
	 * 获取答题卡
	 * @param histId
	 * @return
	 */
	@RequestMapping(value = "student/get-answersheet/{histId}", method = RequestMethod.GET)
	public @ResponseBody AnswerSheet getAnswerSheet(@PathVariable("histId") int histId){
		ExamHistory history = examService.getUserExamHistListByHistId(histId);
		Gson gson = new Gson();
		AnswerSheet answerSheet = gson.fromJson(history.getAnswerSheet(), AnswerSheet.class);
		return answerSheet;
	}
	
	/**
	 * 用户申请考试
	 * @param examId
	 * @return
	 */
	@RequestMapping(value = "student/exam/send-apply/{examId}", method = RequestMethod.GET)
	public @ResponseBody Message sendApply(@PathVariable("examId") int examId){
		Message msg = new Message();
		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		try {
			Exam exam = this.checkExam(examId);
			//申请考试默认未审核
			examService.addUserExamHist(userInfo.getUserid(), examId, exam.getExamPaperId(),0);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			msg.setResult(e.getMessage());
			e.printStackTrace();
		}
		return msg;
	}
	
	/**
	 * 检查用户是否可以申请该考试
	 * @param examId
	 * @return
	 * @throws Exception
	 */
	public Exam checkExam(int examId) throws Exception{
		Exam exam = examService.getExamById(examId);
		if(exam == null){
			throw new Exception("考试不存在！或已经申请过一次！");
		}
		/*if(exam.getEffTime().before(new Date()))
			throw new Exception("不能在考试开始后申请！");*/
		if(exam.getApproved() != 1){
			throw new Exception("不能申请一个未审核通过的考试！");
		}
		
		return exam;
	}
	
	@RequestMapping(value = "/student/exam-submit", method = RequestMethod.POST)
	public @ResponseBody Message finishExam(@RequestBody AnswerSheet answerSheet) {

		Message message = new Message();
		ObjectMapper om = new ObjectMapper();
		try {
			qmqpTemplate.convertAndSend(Constants.ANSWERSHEET_DATA_QUEUE, om.writeValueAsBytes(answerSheet));
		} catch (AmqpException e) {
			e.printStackTrace();
			message.setResult("交卷失败");
			message.setMessageInfo(e.toString());
		} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
			e.printStackTrace();
			message.setResult("交卷失败");
			message.setMessageInfo(e.toString());
		}
		return message;
	}
	
	
	@RequestMapping(value = "addAnswerSheet4Test", method = RequestMethod.GET)
	public @ResponseBody Message addAnswerSheet4Test(Model model) throws JsonProcessingException, IOException {
		Message msg = new Message();
		AnswerSheet as = new AnswerSheet();
		as.setExamPaperId(2);
		ObjectMapper om = new ObjectMapper();
		qmqpTemplate.convertAndSend(Constants.ANSWERSHEET_DATA_QUEUE, om.writeValueAsBytes(as));
		return msg;
	}
	
	/**
	 * 自动或者手动组卷(插入一张空试卷)
	 * 
	 * @param examPaperParam
	 * @return
	 */
	@RequestMapping(value = "student/exampaper-add", method = RequestMethod.POST)
	public @ResponseBody
	Message createExamPaper(@RequestBody PaperCreatorParam param, HttpServletRequest request) {
		
		//一键组卷
		if(param.getQuestionKnowledgePointRate() == null &&
				param.getQuestionTypeNum() == null &&
				param.getQuestionTypePoint() == null &&
				param.getPaperName() == null) {
			String pfx = DateUtil.getString(new Date(), "yyyyMMddhhmmss");
			
			AutoCPaper autoCPaper = examPaperMapper.getAutoPaperById(1);
			
		    HashMap<Integer, Integer> questionTypeNum = new HashMap<Integer, Integer>();
			HashMap<Integer, Float> questionTypePoint = new HashMap<Integer, Float>(),
					questionKnowledgePointRate = new HashMap<Integer, Float>();
			Integer fieldId = Integer.parseInt(request.getSession().getAttribute("fieldId")+"");
			List<KnowledgePoint> pointList = questionService.getKnowledgePointByFieldId(fieldId, null);
			for(KnowledgePoint kp : pointList){
			questionKnowledgePointRate.put(kp.getPointId(), 0f);
			}
			
			for (String item : autoCPaper.getType_num().split(",")){
				String[] jtem = item.split(":");
				if(Integer.parseInt(jtem[1]) > 0 && Float.parseFloat(jtem[2]) > 0) {
					questionTypeNum.put(Integer.parseInt(jtem[0]), Integer.parseInt(jtem[1]));
					questionTypePoint.put(Integer.parseInt(jtem[0]), Float.parseFloat(jtem[2]));
				}
			}
			
			param.setPaperName(Constants.ALL_FREE_PAPER_PNAME+pfx);
			param.setTime(Integer.parseInt(autoCPaper.getTime()));
			param.setPassPoint(Integer.parseInt(autoCPaper.getPass_point()));
			param.setPaperPoint(Integer.parseInt(autoCPaper.getTotal_point()));
			param.setPaperType(fieldId);
			param.setQuestionKnowledgePointRate(questionKnowledgePointRate);
			param.setQuestionTypeNum(questionTypeNum);
			param.setQuestionTypePoint(questionTypePoint);
		}

		UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		Message message = new Message();
		ExamPaper examPaper = new ExamPaper();
		examPaper.setName(param.getPaperName());
		examPaper.setDuration(param.getTime());
		examPaper.setPass_point(param.getPassPoint());
		examPaper.setField_id(param.getPaperType());
		examPaper.setCreator(userInfo.getUsername());
		examPaper.setTotal_point(param.getPaperPoint());
		examPaper.setIs_subjective(true);
		
		//手工组卷
		if(param.getQuestionKnowledgePointRate().size() == 0){
			try{
				
				examPaperService.insertExamPaper(examPaper);
			}catch(Exception ex){
				message.setResult(ex.getMessage());
			}
			message.setGeneratedId(examPaper.getId());
			return message;
		}
		List<Integer> idList = new ArrayList<Integer>();

		HashMap<Integer, Float> knowledgeMap = param
				.getQuestionKnowledgePointRate();
		Iterator<Integer> it = knowledgeMap.keySet().iterator();
		while(it.hasNext()){
			idList.add(it.next());
		}

		HashMap<Integer, HashMap<Integer, List<QuestionStruts>>> questionMap = questionService
				.getQuestionStrutsMap(idList);
		
		
	
		try{
			//创建考试 并更新状态为已完成
			examPaperService.createExamPaper(questionMap, param.getQuestionTypeNum(),
					param.getQuestionTypePoint(),
					param.getQuestionKnowledgePointRate(), examPaper);
			
			//发布考试
			/******************************************/
			Calendar c = Calendar.getInstance();
			c.add(Calendar.YEAR, 10); //十年
			Exam exam = new Exam();
			exam.setCreator(userInfo.getUserid());
			exam.setApproved(1);
			exam.setEffTime(new Date());
			exam.setExpTime(c.getTime());
			exam.setExamName(examPaper.getName());
			exam.setExamPaperId(examPaper.getId());
			exam.setExamType(110); //自组考试
			examService.addExam(exam);
			/******************************************/
			message.setGeneratedId(examPaper.getId());
		}catch(Exception e){
			//e.printStackTrace();
			message.setResult(e.getMessage());
		}
		
		
		return message;
	}
	
	/** 创建试卷
	 * 
	 * @param model
	 * @param request
	 * @param isfree 是否全自动组卷
	 * @return
	 */
	@RequestMapping(value = "exampaper/exampaper-add/{isfree}", method = RequestMethod.GET)
	private String examPaperAddPage(Model model, HttpServletRequest request,
			@PathVariable("isfree") int isfree){
		/**查询对应题库下的题类型数量**/
		Integer fieldId = Integer.parseInt(request.getSession().getAttribute("fieldId")+"");
		List<QuestionStatistic> typeList = questionMapper.getTypeQuestionStaticByFieldId(fieldId);
		
		String url = "";
		if(isfree == 1){
		List<Field> fieldList = questionService.getAllField(null);
		model.addAttribute("fieldList", fieldList);
		model.addAttribute("questionTypes", typeList);
		
			url += "exampaper-add";
		
		}	
		return url;
	}
	
	@RequestMapping(value = "secure/question/get-knowledge-point/{fieldId}", method = RequestMethod.GET)
	public @ResponseBody Message getQuestionPointByFieldId(@PathVariable int fieldId) {
		Message message = new Message();
		HashMap<Integer, String> pointMap = new HashMap<Integer, String>();
		List<KnowledgePoint> pointList = questionService.getKnowledgePointByFieldId(fieldId, null);
		for (KnowledgePoint point : pointList) {
			pointMap.put(point.getPointId(), point.getPointName());
		}
		message.setObject(pointMap);
		return message;
	}
	
}
